var nextLessonPop = function(nextLessonUrl) {
    window.location.href = nextLessonUrl;
};
var consolePop = function(){
    $(".mm_timemachine").height($(".container-fluid").height() - 48);
    $("#mm_console_popout").show();
};
     
var addScorePop = function(score,timeDelay) { //phenixs
    Phenix.init({
        width: 300,
        height: 330,
        template: document.getElementById('test_template').innerHTML,
        data: {
            color: "#36b14a",
            title: "学完本节",
            description: "积分+" + score
        }
    }).show();
    Phenix.show();
    if(timeDelay != 0){
        setTimeout(function(){Phenix.hide();}, timeDelay);
    }
};

var sharePop = function(isJumpToNextLesson,nextLessonUrl) { //share，rule:10 lessons learned
    Phenix.init({
        width: 500,
        height: 280,
        template: '<div class="mm_temp_title" style="padding:0 20px;font-size:14px;color:#7f7f7f;">大神，代码神功在修炼的过程中，不知少侠感觉如何？<br />有木有感觉代码萌萌哒呢，那你可以点击<a id="mm_temp_share" href="#" style="text-decoration:underline;">分享</a>，把网站告诉你的小伙伴们，或者感觉网站有任何问题也可以点击<a href="http://www.mengma.com/about/#mm_feedback_h1" target="_blank" style="text-decoration:underline;">意见反馈</a>，跟产品汪吐槽</div><a id="mm_tolearn" class="mm_temp_learn" style="cursor:po">我要继续学习</a>',
    }).show();
    $("#mm_temp_share").click(function() {
        Phenix.hide();
        $("#mm_share_popout").modal('show');
    });
    $("#mm_tolearn").click(function() {
        Phenix.hide();
        if(isJumpToNextLesson){
            nextLessonPop(nextLessonUrl);
        }else{
            $("#mm_console_popout").show();
        }
    });
};

var popup = function(color, face, text){
    Phenix.init({
        width: 300,
        height: 330,
        templates : '<div style="font-size:20px;font-family:\'Microsoft YaHei\',\'Helvetica Neue\',Helvetica,Arial,sans-serif;padding:10px 0;color:{{color}};">{{face}}</div><div style="font-size:18px;font-family:\'Microsoft YaHei\',\'Helvetica Neue\',Helvetica,Arial,sans-serif;padding:10px 0;">{{title}}</div><div style="font-size:12px;font-family:\'Microsoft YaHei\',\'Helvetica Neue\',Helvetica,Arial,sans-serif;padding:10px 0;color:#b9b9bd;">{{description}}</div>',
        data: {
            color: color,
            title: face,
            description: text
        }
    }).show();
    setTimeout(function(){Phenix.hide();}, 3000);//??
};
//bind
var bindEmailPop = function(isShare,isJumpToNextLesson,nextLessonUrl) { // send email again
    Phenix.init({
        width: 400,
        height: 420,
        template: '<div class="mm_temp_title">惊现隐藏任务</div><div class="mm_temp_des" style="padding:0 30px;">嗨，大神，您已经学习过4课了，为了更好地通知您最新的课程消息，以及跟进您的学习进度，我们需要对您的邮箱进行验证。</div><div style="margin-top:10px;"><span id="mm_email_tip" style="height:20px;text-align:left;color:#6f6f6f;font-size:12px;width:340px;display:inline-block;"></span><input id="mm_email" type="text" class="form-control" style="margin:0 auto;width:340px;height:40px;margin-bottom:10px;" placeholder="请输入您的邮箱地址" /></div><div class="input-group" id="mm_verify" style="display:none;width:340px;margin:0 auto;"><div class="input-group-addon" style="padding:0; margin:0;"><img src="http://www.mengma.com/api/reg/captcha/" id="mm_img_captcha" onclick="this.src=\'http://www.mengma.com/api/reg/captcha/\'+new Date()*1" style="height:40px;" title="点击刷新验证码" /></div><input class="form-control" type="text" placeholder="请输入验证码（点击图片刷新）" name="captcha" required minlength="1" maxlength="5" listen-to-code="107" id="mm_captcha" style="height:40px;"/></div><div style="margin-top:20px;padding:0 30px;"><a id="mm_goto_mail" class="mm_temp_cancel">以后再说</a><a id="mm_temp_send" class="mm_temp_send">发送验证邮件</a></div>',
    }).show(function(){
        $("#mm_email").focus(function() {
            $("#mm_email_tip").html("");
            $("#mm_verify").show(200);
            $("#mm_email").removeClass("mm_form_error");
        });
        $("#mm_captcha").focus(function() {
            $("#mm_captcha_tip").html("");
            $("#mm_captcha").removeClass("mm_form_error");
        });

        $("#mm_goto_mail").click(function() {
            if(isShare) {
                sharePop(isJumpToNextLesson,nextLessonUrl);
            }else{
                Phenix.hide();
                $("#mm_console_popout").show();
            }
        });
        $("#mm_temp_send").click(function() {
            if (!(/^[\w\-\.]+@[\w\-\.]+(\.\w+)+$/.test($("#mm_email").val()))) {
                $("#mm_email_tip").html("请输入正确的邮箱地址，如xx@xx.com");
                $("#mm_email").addClass("mm_form_error");
            } else if ($("#mm_captcha").val().length == 0) {
                $("#mm_captcha_tip").html("请输入正确的验证码");
                $("#mm_captcha").addClass("mm_form_error");
            } else {
                var email_host = $("#mm_email").val().split("@")[1];
                M.ajax("/api/auth/saveemail", {
                    email: $("#mm_email").val(),
                    captcha: $("#mm_captcha").val()
                }, function(data) {
                    var code = parseInt(data['code']);
                    if (code == 0) {
                        Phenix.init({
                            width: 420,
                            height: 280,
                            template: '<div class="mm_temp_title">发送成功</div><div class="mm_temp_des" style="padding:0 30px;">已经向你的邮箱发送了一封验证邮件，快去查收哦</div><div style="margin-top:20px;padding:0 30px;"><a id="mm_goto_learn" class="mm_temp_cancel" style="width:180px;">知道了，我先学完这节课</a><a id="mm_goto_mail" class="mm_temp_send">前往邮箱</a></div>',
                        }).show();
                        $("#mm_goto_learn").click(function() {
                            if(isShare) {
                                sharePop(isJumpToNextLesson,nextLessonUrl);
                            }else{
                                Phenix.hide();
                                $("#mm_console_popout").show();
                            }
                        });
                        $("#mm_goto_mail").click(function() {
                            window.location.href = "http://mail." + email_host;
                        });
                    } else if (code == 1) {
                        $("#mm_email_tip").html("非法请求！");
                    } else if (code == 2) {
                        $("#mm_img_captcha").attr("src", "http://www.mengma.com/captcha/" + new Date() * 1);
                        $("#mm_captcha").val("");
                        $("#mm_captcha").addClass("mm_form_error");
                    } else if (code == 408) {
                        $("#mm_img_captcha").attr("src", "http://www.mengma.com/captcha/" + new Date() * 1);
                        $("#mm_captcha").val("")
                        $("#mm_email_tip").html("此邮箱已被注册！");
                        $("#mm_email").addClass("mm_form_error");
                    }
                }, function() {
                    popup("#b9b9bd", ":(", "操作失败！可能木有吃药，感觉自己萌萌哒！");
                });
            }
        });
    });//end show
};
    //verify
var verifyEmailPop = function(isJumpToNextLesson, nextLessonUrl, isShare) { //verify, rule: 4 lessons learned
    var $emailSent = false;
    Phenix.init({
        width: 500,
        height: 280,
        template: '<div class="mm_temp_title">激活邮件</div><div class="mm_temp_title" style="padding:0 20px;font-size:14px;color:#7f7f7f;">在萌码学习感觉如何呢？如果觉得不错的话别忘了去激活邮箱哦~</div><div style="margin-top:20px;padding:0 30px;"><a id="mm_resend_email" class="mm_temp_cancel" data-loading-text="发送中..." style="width:160px;">重新发送验证邮件</a><a id="mm_to_learn" class="mm_temp_send">好的，我知道了</a></div>',
    }).show(function() {
        $("#mm_resend_email").click(function() {
            $emailSent = true;
            var $btn = $(this).button("loading");
            Phenix.hide();
            M.ajax("/api/auth/sendverifyemail", {}, function(data) {
                $btn.button('reset');
                var code = parseInt(data['code']);
                if (code == 119) {
                    popup("#36b14a", ":)", "这个邮箱已经通过验证");
                } else if (code == 1) {
                    popup("#b9b9bd", ":(", "发送失败！");
                } else if (code == 0) {
                    popup("#36b14a", ":)", "发送成功，请尽快验证~");
                }else if(code == 403){
                    popup("#36b14a", ":)", "验证码已发送，请直接查看邮箱~");
                }
            });
            if(isShare) {
                setTimeout(function(){sharePop();}, 2000);
            }
        });
        $("#mm_to_learn").click(function() {
            if(isShare) {
                clearTimeout();
                setTimeout(function(){sharePop(isJumpToNextLesson,nextLessonUrl);}, 2000);
            }
            Phenix.hide();
            if(!isJumpToNextLesson) {
                consolePop();
            }else{
                nextLessonPop(nextLessonUrl);
            }
            
        });
    });
};

var lessonPop = function(statusCode, score, isJumpToNextLesson, nextLessonUrl){
	switch(statusCode){
		case '000'://next
            isJumpToNextLesson ? nextLessonPop(nextLessonUrl) : consolePop();
			break;
		case '001'://share
			sharePop(isJumpToNextLesson,nextLessonUrl);
            // setTimeout(function(){isJumpToNextLesson ? nextLessonPop(nextLessonUrl) : consolePop();}, 3000);
			break;
		case '010'://verify email
			verifyEmailPop(isJumpToNextLesson,nextLessonUrl,false);
			break;
		case '011'://verify email,share
			verifyEmailPop(isJumpToNextLesson,nextLessonUrl,true);
			break;
		case '020'://bind email
			bindEmailPop(false,isJumpToNextLesson, nextLessonUrl);
			break;
		case '021'://bind email, share
			bindEmailPop(true,isJumpToNextLesson, nextLessonUrl);
			break;
		case '100'://add score 
			if(score != 0){
				addScorePop(score, 2000);
                if(isJumpToNextLesson){
                    setTimeout(function(){nextLessonPop(nextLessonUrl);}, 2000);
                }else{
                    setTimeout(function(){$("#mm_console_popout").show();}, 2000);
                }
			}else{
                if(isJumpToNextLesson){
                    setTimeout(function(){nextLessonPop(nextLessonUrl);}, 2000);
                }else{
                    setTimeout(function(){$("#mm_console_popout").show();}, 2000);
                }
            }
			break;
        case '101'://add score + share
            if(score != 0){
                addScorePop(score, 2000);
                clearTimeout();
                setTimeout(function(){sharePop(isJumpToNextLesson,nextLessonUrl);}, 3000);
            }else{
                if(isJumpToNextLesson){
                    nextLessonPop(nextLessonUrl);
                }else{
                    setTimeout(function(){$("#mm_console_popout").show();}, 2000);
                }
            }
            break;
		case '110'://add score+verify email
			if(score != 0){
				addScorePop(score, 0);
                clearTimeout();
                setTimeout(function(){verifyEmailPop(isJumpToNextLesson,nextLessonUrl,false);}, 2000);
			}else{
                verifyEmailPop(isJumpToNextLesson,nextLessonUrl,false);
            }
            
			break;
		case '111'://add score+verify email + share
			if(score != 0){
				addScorePop(score, 0);
                setTimeout(function(){verifyEmailPop(isJumpToNextLesson,nextLessonUrl, true);}, 2000);
			}else {
                verifyEmailPop(isJumpToNextLesson,nextLessonUrl, true);
            }
			break;
		case '120'://add score + bind email
			if(score != 0){
				addScorePop(score, 0);
                setTimeout(function(){bindEmailPop(false,isJumpToNextLesson, nextLessonUrl);}, 2000);
			}else{
                bindEmailPop(false,isJumpToNextLesson, nextLessonUrl);
            }
			break;
		case '121'://add score + bind email + share
			if(score != 0){
				addScorePop(score, 0);
                setTimeout(function(){bindEmailPop(true,isJumpToNextLesson, nextLessonUrl);}, 2000);
			}else{
                bindEmailPop(true,isJumpToNextLesson, nextLessonUrl);
            }
			break;
		default:
			// popup("#b9b9bd", ":(", "非法访问");
			break;
	}

}
ifvisible.setIdleDuration(300);
/* 休眠 */
ifvisible.idle(function(){
    addLeaveFlag();
});
/** end Learn **/
window.onbeforeunload = function(event){
    /* 用户点击浏览器右上角关闭按钮或者按alt+F4关闭*/
    if (event.clientX > document.body.clientWidth && event.clientY < 0 || event.altKey) {
        event.returnValue = "浏览器关闭";
    /*用户点击任务栏，右键关闭。S或是按下alt+F4关闭*/
    }else if(event.clientY > document.body.clientHeight || event.altKey){
        event.returnValue = "确定要从任务栏离开当前页面吗";
    } else {
        addLeaveFlag();
    }　　　
}

function addLeaveFlag(){
    var url = 'http://s.mengma.com/img/mm_avatar/leaveFlag.png?' + new Date();
    var img = new Image();
    img.src = url;
    setTimeout(function() {}, 1000);
}